//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 1995-2000, The Hypersonic SQL Group.
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the Hypersonic SQL Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE HYPERSONIC SQL GROUP,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * on behalf of the Hypersonic SQL Group.
 *
 *
 * For work added by the HSQL Development Group:
 *
 * Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using System.Text;
using System.Collections.Generic;
using EffiProz.Core.Errors;
using EffiProz.Core.Lib;

namespace EffiProz.Core.Rights
{

    // fredt@users 20021103 - patch 1.7.2 - fix bug _in revokeAll()
    // fredt@users 20021103 - patch 1.7.2 - allow for drop table, etc.
    // when tables are dropped or renamed, changes are reflected _in the
    // permissions held _in User objects.
    // boucherb@users 200208-200212 - doc 1.7.2 - update
    // boucherb@users 200208-200212 - patch 1.7.2 - metadata
    // unsaved@users - patch 1.8.0 moved right managament to new classes

    /**
     * A User Object holds the name, password for a
     * particular database user.<p>
     *
     * Enhanced _in successive versions of HSQLDB.
     *
     * @author Thomas Mueller (Hypersonic SQL Group)
     * @version 1.8.0
     * @since Hypersonic SQL
     */
    public class User : Grantee
    {

        /** password. */
        private String password;

        /** default schema when new Sessions started (defaults to PUBLIC schema) */
        private QNameManager.QName initialSchema = null;

        /**
         * Constructor
         */
        public User(QNameManager.QName name, GranteeManager manager)
            : base(name, manager)
        {



            if (manager != null)
            {
                updateAllRights();
            }
        }

        public override String getSQL()
        {

            StringBuilder sb = new StringBuilder();

            sb.Append(Tokens.T_CREATE).Append(' ').Append(Tokens.T_USER);
            sb.Append(' ').Append(granteeName.statementName).Append(' ');
            sb.Append(Tokens.T_PASSWORD).Append(' ');
            sb.Append('\'').Append(password).Append('\'');

            return sb.ToString();
        }

        public void setPassword(String password)
        {

            /** @todo - introduce complexity interface */

            // checkComplexity(password);
            // requires: UserManager.createSAUser(), UserManager.createPublicUser()
            this.password = password;
        }

        /**
         * Checks if this object's password attibute equals
         * specified argument, else throws.
         */
        public void checkPassword(String value)
        {

            if (!value.Equals(password))
            {
                throw Error.error(ErrorCode.X_28000);
            }
        }

        /**
         * Returns the initial schema for the user
         */
        public QNameManager.QName getInitialSchema()
        {
            return initialSchema;
        }

        public QNameManager.QName getInitialOrDefaultSchema()
        {

            if (initialSchema != null)
            {
                return initialSchema;
            }

            QNameManager.QName schema =
                granteeManager.database.schemaManager.findSchemaHsqlName(
                    getNameString());

            if (schema == null)
            {
                return granteeManager.database.schemaManager
                    .getDefaultSchemaHsqlName();
            }
            else
            {
                return schema;
            }
        }

        /**
         * This class does not have access to the SchemaManager, therefore
         * caller should verify that the given schemaName exists.
         *
         * @param schema An existing schema.  Null value allowed,
         *                   which means use the DB default session schema.
         */
        public void setInitialSchema(QNameManager.QName schema)
        {
            initialSchema = schema;
        }

        /**
         * Returns the ALTER USER DDL character sequence that preserves the
         * this user's current password value and mode. <p>
         *
         * @return  the DDL
         */
        public String getAlterUserSQL()
        {

            StringBuilder sb = new StringBuilder();

            sb.Append(Tokens.T_ALTER).Append(' ');
            sb.Append(Tokens.T_USER).Append(' ');
            sb.Append(getStatementName()).Append(' ');
            sb.Append(Tokens.T_SET).Append(' ');
            sb.Append(Tokens.T_PASSWORD).Append(' ');
            sb.Append('"').Append(password).Append('"');

            return sb.ToString();
        }

        public String getInitialSchemaSQL()
        {

            StringBuilder sb = new StringBuilder();

            sb.Append(Tokens.T_ALTER).Append(' ');
            sb.Append(Tokens.T_USER).Append(' ');
            sb.Append(getStatementName()).Append(' ');
            sb.Append(Tokens.T_SET).Append(' ');
            sb.Append(Tokens.T_INITIAL).Append(' ');
            sb.Append(Tokens.T_SCHEMA).Append(' ');
            sb.Append(initialSchema.statementName);

            return sb.ToString();
        }

        /**
         * Returns the DDL string
         * sequence that creates this user.
         *
         */
        public String getCreateUserSQL()
        {

            StringBuilder sb = new StringBuilder(64);

            sb.Append(Tokens.T_CREATE).Append(' ');
            sb.Append(Tokens.T_USER).Append(' ');
            sb.Append(getStatementName()).Append(' ');
            sb.Append(Tokens.T_PASSWORD).Append(' ');
            sb.Append(StringConverter.toQuotedString(password, '"', true));

            return sb.ToString();
        }

        /**
         * Retrieves the redo log character sequence for connecting
         * this user
         *
         * @return the redo log character sequence for connecting
         *      this user
         */
        public String getConnectUserSQL()
        {

            StringBuilder sb = new StringBuilder();

            sb.Append(Tokens.T_SET).Append(' ');
            sb.Append(Tokens.T_SESSION).Append(' ');
            sb.Append(Tokens.T_AUTHORIZATION).Append(' ');
            sb.Append(StringConverter.toQuotedString(getNameString(), '\'', true));

            return sb.ToString();
        }
    }
}
